<template>
  <view class="event-management-page">
    <!-- 导航栏 -->
    <u-navbar title="事件管理" back-icon="arrow-left" />
    
    <!-- 筛选区域 -->
    <view class="filter-section">
      <view class="filter-row">
        <u-input
          v-model="filterForm.title"
          placeholder="请输入事件标题"
          class="filter-input"
          @input="handleSearch"
        />
        <u-button 
          type="primary" 
          text="搜索" 
          size="mini"
          @click="handleSearch"
        />
      </view>
      <view class="filter-row">
        <u-picker
          :show="showTypePicker"
          :columns="typeColumns"
          @confirm="onTypeConfirm"
          @cancel="showTypePicker = false"
          title="选择事件类型"
        />
        <u-input
          v-model="filterForm.eventTypeText"
          placeholder="事件类型"
          readonly
          @click="showTypePicker = true"
          class="filter-input"
        />
        <u-picker
          :show="showSeverityPicker"
          :columns="severityColumns"
          @confirm="onSeverityConfirm"
          @cancel="showSeverityPicker = false"
          title="选择严重程度"
        />
        <u-input
          v-model="filterForm.severityText"
          placeholder="严重程度"
          readonly
          @click="showSeverityPicker = true"
          class="filter-input"
        />
      </view>
      <view class="filter-row">
        <u-picker
          :show="showStatusPicker"
          :columns="statusColumns"
          @confirm="onStatusConfirm"
          @cancel="showStatusPicker = false"
          title="选择状态"
        />
        <u-input
          v-model="filterForm.statusText"
          placeholder="状态"
          readonly
          @click="showStatusPicker = true"
          class="filter-input"
        />
        <u-input
          v-model="filterForm.startDate"
          placeholder="开始日期"
          readonly
          @click="showStartDatePicker = true"
          class="filter-input"
        />
        <u-input
          v-model="filterForm.endDate"
          placeholder="结束日期"
          readonly
          @click="showEndDatePicker = true"
          class="filter-input"
        />
      </view>
    </view>

    <!-- 列表区域 -->
    <scroll-view 
      scroll-y="true" 
      class="list-scroll" 
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <view class="list-content">
        <!-- 事件列表 -->
        <view 
          v-for="item in eventList" 
          :key="item.id"
          class="event-card"
          @click="goToEventDetail(item.id)"
        >
          <view class="card-header">
            <view class="header-left">
              <text class="event-title">{{ item.title }}</text>
              <u-tag 
                :text="getEventTypeText(item.eventType)" 
                type="info" 
                size="mini"
                class="type-tag"
              />
            </view>
            <view class="header-right">
              <u-tag 
                :text="getSeverityText(item.severity)" 
                :type="getSeverityType(item.severity)" 
                size="mini"
                class="severity-tag"
              />
            </view>
          </view>
          
          <view class="card-content">
            <view class="content-item">
              <u-icon name="map-pin" size="14" color="#666" class="item-icon"></u-icon>
              <text class="item-text">{{ item.location || '未知地点' }}</text>
            </view>
            <view class="content-item">
              <u-icon name="user" size="14" color="#666" class="item-icon"></u-icon>
              <text class="item-text">报告人：{{ item.reporterName || '未知' }}</text>
            </view>
            <view class="content-item">
              <u-icon name="clock" size="14" color="#666" class="item-icon"></u-icon>
              <text class="item-text">{{ formatTime(item.eventTime) }}</text>
            </view>
            <view class="content-item" v-if="item.description">
              <u-icon name="file-text" size="14" color="#666" class="item-icon"></u-icon>
              <text class="item-text">{{ item.description }}</text>
            </view>
          </view>
          
          <!-- 图片预览区域 -->
          <view class="image-section" v-if="item.photos">
            <view class="image-title">现场照片</view>
            <view class="image-grid">
              <view 
                v-for="(photo, index) in getPhotos(item.photos)" 
                :key="index"
                class="image-item"
                @click.stop="previewImage(photo, index)"
              >
                <image :src="getImageUrl(photo)" mode="aspectFill" class="preview-image" />
              </view>
            </view>
          </view>
          
          <view class="card-footer">
            <view class="status-info">
              <text class="status-text">{{ getStatusText(item.status) }}</text>
              <view class="status-indicator" :class="getStatusClass(item.status)"></view>
            </view>
            
            <view class="action-buttons">
              <u-button 
                v-if="item.status === 1"
                type="primary" 
                text="处理"
                size="mini"
                @click.stop="goToEventHandle(item.id)"
                class="action-btn"
              />
              <u-button 
                v-else
                type="info" 
                text="详情"
                size="mini"
                @click.stop="goToEventDetail(item.id)"
                class="action-btn"
              />
            </view>
          </view>
        </view>
        
        <!-- 空状态 -->
        <view v-if="eventList.length === 0 && !loading" class="empty-state">
          <u-empty text="暂无事件数据" icon="alert-circle" mode="list" />
        </view>
        
        <!-- 加载更多提示 -->
        <view v-if="eventList.length > 0" class="load-more-tip">
          <text v-if="loading" class="tip-text">加载中...</text>
          <text v-else-if="hasMore" class="tip-text">上拉加载更多</text>
          <text v-else class="tip-text">没有更多数据了</text>
        </view>
      </view>
    </scroll-view>

    <!-- 上报事件按钮 -->
    <view class="report-event-button" @click="goToEventReport">
      <u-icon name="plus" color="#fff" size="24"></u-icon>
      <text class="button-text">上报事件</text>
    </view>

    <!-- 日期选择器 -->
    <u-datetime-picker
      :show="showStartDatePicker"
      v-model="startDateValue"
      mode="date"
      @confirm="onStartDateConfirm"
      @cancel="showStartDatePicker = false"
      title="选择开始日期"
    />
    
    <u-datetime-picker
      :show="showEndDatePicker"
      v-model="endDateValue"
      mode="date"
      @confirm="onEndDateConfirm"
      @cancel="showEndDatePicker = false"
      title="选择结束日期"
    />
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { getSecurityEventPage } from '@/api/security'

// 响应式数据
const eventList = ref([])
const loading = ref(false)
const refreshing = ref(false)
const hasMore = ref(true)

// 分页数据
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 筛选表单
const filterForm = reactive({
  title: '',
  eventType: '',
  eventTypeText: '',
  severity: '',
  severityText: '',
  status: '',
  statusText: '',
  startDate: '',
  endDate: ''
})

// 选择器显示状态
const showTypePicker = ref(false)
const showSeverityPicker = ref(false)
const showStatusPicker = ref(false)
const showStartDatePicker = ref(false)
const showEndDatePicker = ref(false)

// 日期值
const startDateValue = ref('')
const endDateValue = ref('')

// 选择器数据
const typeColumns = ref([[
  { label: '可疑人员', value: 'suspicious' },
  { label: '设施损坏', value: 'damage' },
  { label: '消防隐患', value: 'fire' },
  { label: '其他', value: 'other' }
]])

const severityColumns = ref([[
  { label: '一般', value: 1 },
  { label: '重要', value: 2 },
  { label: '紧急', value: 3 }
]])

const statusColumns = ref([[
  { label: '待处理', value: 1 },
  { label: '处理中', value: 2 },
  { label: '已处理', value: 3 },
  { label: '已关闭', value: 4 }
]])

// 页面加载时获取数据
onMounted(() => {
  loadEventList()
})

/**
 * 加载事件列表
 */
const loadEventList = async (isRefresh = false) => {
  try {
    if (isRefresh) {
      pagination.pageNum = 1
      eventList.value = []
      hasMore.value = true
    }
    
    loading.value = true
    const params = {
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
      title: filterForm.title,
      eventType: filterForm.eventType,
      severity: filterForm.severity,
      status: filterForm.status,
      startDate: filterForm.startDate,
      endDate: filterForm.endDate
    }
    
    const response = await getSecurityEventPage(params)
    if (response.success && response.data) {
      const { records, total } = response.data
      
      if (isRefresh) {
        eventList.value = records || []
      } else {
        eventList.value.push(...(records || []))
      }
      
      pagination.total = total || 0
      hasMore.value = eventList.value.length < pagination.total
    }
  } catch (error) {
    console.error('加载事件列表失败:', error)
    uni.showToast({
      title: '加载失败，请重试',
      icon: 'none'
    })
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

/**
 * 搜索处理
 */
const handleSearch = () => {
  loadEventList(true)
}

/**
 * 类型选择确认
 */
const onTypeConfirm = (event) => {
  const selectedType = event.value[0]
  filterForm.eventType = selectedType.value
  filterForm.eventTypeText = selectedType.label
  showTypePicker.value = false
  loadEventList(true)
}

/**
 * 严重程度选择确认
 */
const onSeverityConfirm = (event) => {
  const selectedSeverity = event.value[0]
  filterForm.severity = selectedSeverity.value
  filterForm.severityText = selectedSeverity.label
  showSeverityPicker.value = false
  loadEventList(true)
}

/**
 * 状态选择确认
 */
const onStatusConfirm = (event) => {
  const selectedStatus = event.value[0]
  filterForm.status = selectedStatus.value
  filterForm.statusText = selectedStatus.label
  showStatusPicker.value = false
  loadEventList(true)
}

/**
 * 开始日期确认
 */
const onStartDateConfirm = (event) => {
  filterForm.startDate = event.value
  showStartDatePicker.value = false
  loadEventList(true)
}

/**
 * 结束日期确认
 */
const onEndDateConfirm = (event) => {
  filterForm.endDate = event.value
  showEndDatePicker.value = false
  loadEventList(true)
}

/**
 * 下拉刷新
 */
const onRefresh = () => {
  refreshing.value = true
  loadEventList(true)
}

/**
 * 加载更多
 */
const loadMore = () => {
  if (!loading.value && hasMore.value) {
    pagination.pageNum++
    loadEventList()
  }
}

/**
 * 获取事件类型文本
 */
const getEventTypeText = (type) => {
  const typeMap = {
    'suspicious': '可疑人员',
    'damage': '设施损坏',
    'fire': '消防隐患',
    'other': '其他'
  }
  return typeMap[type] || '未知类型'
}

/**
 * 获取严重程度文本
 */
const getSeverityText = (severity) => {
  const severityMap = {
    1: '一般',
    2: '重要',
    3: '紧急'
  }
  return severityMap[severity] || '未知'
}

/**
 * 获取严重程度类型
 */
const getSeverityType = (severity) => {
  const typeMap = {
    1: 'info',
    2: 'warning',
    3: 'error'
  }
  return typeMap[severity] || 'info'
}

/**
 * 获取状态文本
 */
const getStatusText = (status) => {
  const statusMap = {
    1: '待处理',
    2: '处理中',
    3: '已处理',
    4: '已关闭'
  }
  return statusMap[status] || '未知状态'
}

/**
 * 获取状态样式类
 */
const getStatusClass = (status) => {
  const classMap = {
    1: 'status-pending',
    2: 'status-processing',
    3: 'status-completed',
    4: 'status-closed'
  }
  return classMap[status] || 'status-unknown'
}

/**
 * 获取照片列表
 */
const getPhotos = (photos) => {
  if (!photos) return []
  try {
    const data = typeof photos === 'string' ? JSON.parse(photos) : photos
    return Array.isArray(data) ? data : []
  } catch (error) {
    return []
  }
}

/**
 * 获取图片URL
 */
const getImageUrl = (imageData) => {
  if (!imageData) return ''
  try {
    const data = typeof imageData === 'string' ? JSON.parse(imageData) : imageData
    return data.fileUrl || data.url || imageData
  } catch (error) {
    return imageData
  }
}

/**
 * 预览图片
 */
const previewImage = (imageData, index) => {
  const imageUrl = getImageUrl(imageData)
  if (imageUrl) {
    uni.previewImage({
      urls: [imageUrl],
      current: imageUrl
    })
  }
}

/**
 * 格式化时间
 */
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 页面导航方法
const goToEventDetail = (id) => {
  uni.navigateTo({
    url: `/pages/property-work/security-management/event-detail?id=${id}`
  })
}

const goToEventHandle = (id) => {
  uni.navigateTo({
    url: `/pages/property-work/security-management/event-handle?id=${id}`
  })
}

const goToEventReport = () => {
  uni.navigateTo({
    url: '/pages/property-work/security-management/event-report'
  })
}
</script>

<style lang="scss" scoped>
.event-management-page {
  min-height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.filter-section {
  background: white;
  padding: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  .filter-row {
    display: flex;
    align-items: center;
    gap: 16rpx;
    margin-bottom: 16rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .filter-input {
      flex: 1;
    }
  }
}

.list-scroll {
  flex: 1;
  min-height: 0;
}

.list-content {
  padding: 20rpx;
}

.event-card {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.98);
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
    
    .header-left {
      display: flex;
      align-items: center;
      gap: 16rpx;
      
      .event-title {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
      }
      
      .type-tag {
        flex-shrink: 0;
      }
    }
    
    .header-right {
      .severity-tag {
        flex-shrink: 0;
      }
    }
  }
  
  .card-content {
    margin-bottom: 20rpx;
    
    .content-item {
      display: flex;
      align-items: center;
      gap: 12rpx;
      margin-bottom: 12rpx;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .item-icon {
        flex-shrink: 0;
      }
      
      .item-text {
        font-size: 26rpx;
        color: #666;
        line-height: 1.4;
        word-break: break-all;
      }
    }
  }
  
  .image-section {
    margin-bottom: 20rpx;
    
    .image-title {
      font-size: 26rpx;
      color: #333;
      margin-bottom: 12rpx;
    }
    
    .image-grid {
      display: flex;
      gap: 16rpx;
      flex-wrap: wrap;
      
      .image-item {
        width: 120rpx;
        height: 120rpx;
        border-radius: 8rpx;
        overflow: hidden;
        
        .preview-image {
          width: 100%;
          height: 100%;
        }
      }
    }
  }
  
  .card-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .status-info {
      display: flex;
      align-items: center;
      gap: 12rpx;
      
      .status-text {
        font-size: 24rpx;
        color: #666;
      }
      
      .status-indicator {
        width: 12rpx;
        height: 12rpx;
        border-radius: 50%;
        
        &.status-pending {
          background: #ffa502;
        }
        
        &.status-processing {
          background: #3498db;
        }
        
        &.status-completed {
          background: #2ed573;
        }
        
        &.status-closed {
          background: #95a5a6;
        }
        
        &.status-unknown {
          background: #bdc3c7;
        }
      }
    }
    
    .action-buttons {
      .action-btn {
        min-width: 120rpx;
      }
    }
  }
}

.empty-state {
  padding: 100rpx 0;
  text-align: center;
}

.load-more-tip {
  padding: 30rpx 0;
  text-align: center;
  
  .tip-text {
    font-size: 24rpx;
    color: #999;
  }
}

.report-event-button {
  position: fixed;
  bottom: 40rpx;
  right: 40rpx;
  background: linear-gradient(135deg, #ff4757 0%, #ff6b7a 100%);
  border-radius: 50rpx;
  padding: 20rpx 30rpx;
  display: flex;
  align-items: center;
  gap: 12rpx;
  box-shadow: 0 4rpx 20rpx rgba(255, 71, 87, 0.4);
  z-index: 999;
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.95);
  }
  
  .button-text {
    color: white;
    font-size: 28rpx;
    font-weight: 600;
  }
}
</style>
